package project.suntray.com.core.net.download;

import commerce.zhangyang.com.core.net.RestCreator;
import commerce.zhangyang.com.core.net.callback.IError;
import commerce.zhangyang.com.core.net.callback.IFailure;
import commerce.zhangyang.com.core.net.callback.IRequest;
import commerce.zhangyang.com.core.net.callback.ISuccess;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.WeakHashMap;

/**
 * Created by ASUS on 2017/12/19.
 */
public final class DownloadHandler {

    private final String URL;
    private static final WeakHashMap<String,Object> PARAMS= RestCreator.getParams();
    private final IRequest REQUEST;
    private final String DOWNLOAD_DIR;
    private final String EXTENSION;
    private final String NAME;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;


    public DownloadHandler(String url,
                           IRequest request,
                           String download_dir,
                           String extension,
                           String name,
                           ISuccess success,
                           IFailure failure,
                           IError error) {
        URL = url;
        REQUEST = request;
        DOWNLOAD_DIR = download_dir;
        EXTENSION = extension;
        NAME = name;
        SUCCESS = success;
        FAILURE = failure;
        ERROR = error;
    }

    /**
     * 处理下载
     */
    public final void handleDownload() {
        //处理开始下载
        if (REQUEST != null) {
            REQUEST.onRequestStart();
        }

        //请求creator
        RestCreator.getRestService()
                    .downLoad(URL,PARAMS)
                    .enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if(response.isSuccessful()){
                                //请求成功
                                final ResponseBody responseBody=response.body();
//                                final
                            }else{
                                //请求失败
                                if(ERROR!=null){
                                    ERROR.onError(response.code(),response.message());
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable throwable) {

                        }
                    });
    }
}
